<style lang="less">
    @import './index.less';
</style>

<template>
    <div class="user-list-view">
        <Card>
            <p slot="title">用户列表</p>
            <span slot="extra">
                <Button icon="loop" type="success" size="small" @click.prevent="getData">刷新列表</Button>
                <Button icon="plus" type="success" size="small" @click.prevent="showAddUserModel">添加用户</Button>
            </span>
            <Row>
                <Col>
                    <Table border="true" :loading="loading" stripe="true" height="450" :context="self" :columns="columns" :data="data"></Table>
                </Col>
            </Row>
            <Row style="padding: 5px 0">
                <Col>
                    <Page ref="Page"
                          :total="page.total"
                          :size="page.size"
                          @on-change="handleChangePage"
                          @on-page-size-change="handleChangePageSize"
                          :page-size-opts="page.sizes" show-sizer show-elevator></Page>
                </Col>
            </Row>
        </Card>

        <Modal ref="editModel" v-model="editModel">
            <p slot="header" style="color:#f60;text-align:center">
                <span>修改用户信息</span>
            </p>
            <div style="text-align:center">
                <editForm :row.sync="editRow" :row-index.sync="editRowIndex" :root-node="this" @on-change="handleEdited"></editForm>
            </div>
            <div slot="footer"></div>
        </Modal>


        <Modal ref="addModel" v-model="addModel" style="width: 480px;">
            <p slot="header" style="text-align:center">
                <span>添加用户</span>
            </p>
            <div style="text-align:center">
                <addForm :root-node="this" @on-change="handleAdded"></addForm>
            </div>
            <div slot="footer"></div>
        </Modal>

        <Modal ref="roleModel" v-model="roleModel" style="width: 480px;" @on-ok="roleAttachPost">
            <p slot="header" style="text-align:center">
                <span>修改角色</span>
            </p>
            <div style="text-align:center">
                <Select v-model="selectedRole" style="width:200px" multiple>
                    <Option v-for="item in roles" :value="item.id" :key="item.id">{{ item.display_name }}</Option>
                </Select>
            </div>
        </Modal>


    </div>
</template>

<script>
    import util from '@/libs/util';
    import expandRow from './ExpandRow.vue';
    import editForm from './EditForm.vue';
    import addForm from './AddForm.vue';

    const editButton = (vm, h, row, index) => {
        return h('a', {
            style: {
                margin: '5px'

            },
            on: {
                'click': (event) => {
                    vm.edit(row, index)
                }
            }
        }, '修改');
    };

    const roleButton = (vm, h, row, index) => {
        return h('a', {
            style: {
                margin: '5px'

            },
            on: {
                'click': (event) => {
                    vm.roleAttach(row, index)
                }
            }
        }, '修改角色');
    };

    const toggleStatusButton = (vm, h, row, index) => {
        return h('Poptip', {
            props: {
                confirm: true,
                title: '您确定要修改该用户的账号状态吗?',
                transfer: true
            },
            on: {
                'on-ok': () => {
                    vm.updateStatus(row, index);
                }
            }
        }, [
            h('a', {
                style: {
                    margin: '5px',
                    color: row.is_effect ? 'red' : 'green'
                }
            }, row.is_effect ? '禁用' : '启用')
        ]);
    };

    export default {
        components: {
            expandRow,
            editForm,
            addForm
        },

        data () {
            return {
                self: this,
                loading: false,
                editModel: false,
                editRow: {},
                editRowIndex: '',
                addModel: false,
                roleModel: false,
                roleUserId: '',
                roles: [],
                selectedRole: [],
                page: {
                    total: 0,
                    current: 1,
                    size: 10,
                    sizes: [10, 30, 50, 100],
                },
                columns: [
                    {
                        type: 'expand',
                        width: 50,
                        render: (h, params) => {
                            return h(expandRow, {
                                props: {
                                    row: params.row
                                }
                            })
                        }
                    },
                    {
                        title: '用户ID',
                        key: 'id',
                        width: 80
                    },
                    {
                        title: '账号',
                        key: 'name',
                    },
                    {
                        title: '邮箱',
                        key: 'email'
                    },
                    {
                        title: '角色',
                        key: 'roles_text'
                    },
                    {
                        title: '姓名',
                        key: 'realname'
                    },
                    {
                        title: '电话',
                        key: 'mobile'
                    },
                    {
                        title: '来源',
                        key: 'source_text',
                        width: 120,
                    },
                    {
                        title: '状态',
                        key: 'is_effect',
                        width: 80,
                    },
                    {
                        title: '操作',
                        key: 'action',
                        width: 150,
                        align: 'center'
                    }
                ],
                data: []
            }
        },

        created () {
            this.init();
        },

        mounted () {
            this.getData();
        },

        watch: {
            'page': (page) => {
                this.$refs.Page.total = page.total;
                this.$refs.Page.current = page.current;
            }
        },

        methods: {
            init () {
                let vm = this;

                this.columns.forEach(item => {
                    if (item.key == 'action') {
                        item.render = (h, param) => {
                            return [
                                roleButton(vm, h, param.row, param.index),
                                editButton(vm, h, param.row, param.index),
                                toggleStatusButton(vm, h, param.row, param.index),
                            ]
                        };
                    }

                    if (item.key == 'is_effect') {
                        item.render = (h, param) => {
                          if (param.row.is_effect == 1) {
                              return h('span', {
                                  style: {
                                      color: 'green'
                                  }
                              }, '已启用');
                          } else {
                              return h('span', {
                                  style: {
                                      color: 'red'
                                  }
                              }, '已禁用');
                          }
                        };
                    }
                });
            },

            getData () {
                this.$Message.loading('数据加载中...');
                this.loading = true;
                util.api().get(`/admin/api/admins?page=${this.page.current}`, {
                    headers: {
                        pageSize: this.page.size,
                    }
                }).then((resp) => {
                    this.$Message.destroy();
                    if (resp.data.status == true) {
                        this.data = resp.data.data;
                        this.page.total = resp.data.meta.total;
                        this.page.current = resp.data.meta.current_page;
                    } else {
                        this.$Message.error(resp.data.message);
                    }
                    this.loading = false;
                }).catch((e) => {
                    this.$Message.destroy();
                    if (e.response) {
                        this.$Notice.error({ title: '网络请求异常', desc: e.response.data.message});
                    } else {
                        this.$Message.error('网络请求错误');
                    }
                    this.loading = false;
                });
            },

            handleChangePage (page) {
                this.page.current = page;
                this.getData();
            },

            handleChangePageSize (size) {
                this.page.size = size;
                this.getData();
            },

            handleEdited(row, index) {
                this.data[index] = row;
            },

            edit (row, index) {
                this.editModel = true;
                this.editRow = row;
                this.editRowIndex = index;
            },

            updateStatus (row, index) {
                let newStatus = row.is_effect == 1 ? 0 : 1;

                util.api().patch(`/admin/api/admins/${row.id}/status/${newStatus}`).then((resp) => {
                   if (resp.data.status == true) {
                       this.data[index].is_effect = newStatus;
                       this.$Message.success(resp.data.message);
                   } else {
                       this.$Message.error(resp.data.message);
                   }
                }).catch((e) => {
                    if (e.response) {
                        if (e.response.status == 422) {
                            if (e.response.data.hasOwnProperty('errors')) {
                                for (let i in e.response.data.errors) {
                                    this.$Notice.error({ title: '表单数据验证失败', desc: e.response.data.errors[i][0] });
                                }
                            }
                        } else {
                            this.$Message.error(e.response.data.message);
                        }
                    }  else {
                        this.$Message.error('网络请求异常');
                    }
                });
            },

            showAddUserModel () {
                this.addModel = true;
            },

            handleAdded(data) {
                this.data.push(data);
            },

            roleAttach (row, index) {
                util.api().get('/admin/api/roles').then((resp) => {
                    this.roles = resp.data.data.filter(item => !util.oneOf(item.name, ['web', 'agent']));
                    this.roleModel = true;
                    let selectedRole = [];
                    for (let i in row.roles) {
                        selectedRole.push(row.roles[i].id);
                    }

                    this.roleUserId = row.id;
                    this.selectedRole = selectedRole;
                }).catch((e) => {
                    util.handleApiException(e, this, '获取角色信息失败');
                })
            },

            roleAttachPost () {
                const roleIds = this.selectedRole.join(',');

                util.api().patch(`/admin/api/admins/roles/${this.roleUserId}/${roleIds}`).then((resp) => {
                    if (resp.data.status == true) {
                        this.$Notice.success({ title: resp.data.message });
                        this.getData();
                    }
                }).catch((e) => {
                    util.handleApiException(e, this, '获取角色信息失败');
                })
            }
        }
    };
</script>
